package com.feihao.zhou.TCP.demoFileUpLoadUseThread;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class SocketThread implements Runnable {
    private Socket accept;

    //通过构造方法给accep赋值：！！！！！！！！


    public SocketThread(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        BufferedWriter bw = null;

        try {
            //创建网络读取流，读取客户端创入的文件：：
            InputStream is = accept.getInputStream();

            //创建本地文件写入流，将读取的文件 写入网络服务器中：
            bos = new BufferedOutputStream(new FileOutputStream(
                    "D:\\IdeaProjects\\Job-code\\day16-code-NET\\upLoadDir\\" + UUID.randomUUID().toString() + ".pdf"));

            //一读一写：
            int b;
            byte[] bytes = new byte[1024];

            while ((b = is.read(bytes)) != -1) {
                //写入：
                bos.write(bytes, 0, b);
            }

            //写完给客户端回文：
            bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            bw.write("上传成功！！！");
            bw.newLine();
            bw.flush();


            //关闭资源：
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
